package com.fhz.mvitest2.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.fhz.mvitest.model.BannerRepostory
import com.fhz.mvitest.model.LoginRepostory
import com.fhz.mvitest2.intent.BannerIntent
import com.fhz.mvitest2.intent.LoginIntent
import com.fhz.mvitest2.state.LoginUIState
import com.fhz.mvitest2.ui.BannerUIState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * 时间:2023/5/23
 * @author Mr.Feng
 * 简述: TODO
 */
@HiltViewModel
class LoginViewModel @Inject constructor (var repostory: LoginRepostory) :ViewModel() {

    val channel = Channel<LoginIntent>(Channel.UNLIMITED)
    //不让外部调用
    private val _state = MutableStateFlow<LoginUIState>(LoginUIState.Init)
    //使用flow来监听
    val state: StateFlow<LoginUIState>
        get() = _state


    init {
        handleIntent()
    }

    //用户意图
    private fun handleIntent() {
        viewModelScope.launch {
            channel.consumeAsFlow().collect{
                when(it){
                    is LoginIntent.Login -> login(it)
                    is LoginIntent.Logout -> logout()
                }
            }
        }
    }

    private fun logout() {

    }

    private fun login(i:LoginIntent.Login) {
        viewModelScope.launch {
            val login = repostory.login(i.name, i.pwd)
            if(login.errorCode == 200){
               _state.value = LoginUIState.Success(login)
            }else{
               _state.value = LoginUIState.Fail(login)
            }
        }
    }

}